package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapperUtil {
	/**
	 * 该工具方法，实现对象与json数据的转化
	 */
	private static final ObjectMapper MAPPER=new ObjectMapper();
	/**
	 * 将对象转成json	
	 */
	public static String toJson(Object obj) {
		try {
			String json = MAPPER.writeValueAsString(obj);
			return json;
		} catch (JsonProcessingException e){
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	/**
	 * 将json转成对象	
	 */

	/*
	 * public static Object toObject(String json,Class<?> targetClass) { try {
	 * Object object = MAPPER.readValue(json, targetClass); return object; }
	 * catch(JsonProcessingException e) { e.printStackTrace(); throw new
	 * RuntimeException(e); }
	 * 
	 * }
	 */

	
	  public static <T> T toObject(String json,Class<T> targetClass) { 
		  try { 
			  T t=MAPPER.readValue(json, targetClass); 
			  return t; 
			  } catch(JsonProcessingException e) { 
				  e.printStackTrace(); 
				  throw new RuntimeException(e); } }
	 
}
